﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.Linq;


[ExecuteInEditMode]
public class ShadowCam : MonoBehaviour {

	// Depth
	// Position
	// Normal
	// Flux
	[HideInInspector]
	public List<RenderTexture> RSMBuffers { get; private set; }

	Camera m_cam;

	private void Start() {
		m_cam = m_cam ?? GetComponent<Camera>();
		RSMBuffers = new List<RenderTextureFormat> {
			RenderTextureFormat.RFloat,
			RenderTextureFormat.ARGBFloat,
			RenderTextureFormat.ARGBFloat,
			RenderTextureFormat.ARGBFloat,
		}.ConvertAll(fmt => {
			var desc = new RenderTextureDescriptor(m_cam.pixelWidth, m_cam.pixelHeight, fmt, 0);
			desc.sRGB = false;
			desc.useMipMap = false;
			var buf = new RenderTexture(desc);
			buf.Create();
			return buf;
		});
		RSMBuffers.Add(new RenderTexture(m_cam.pixelWidth, m_cam.pixelHeight, 24, RenderTextureFormat.Default, RenderTextureReadWrite.Linear));
		//m_cam.SetTargetBuffers(new RenderBuffer[] {
		//	RSMBuffers[0].colorBuffer,
		//	RSMBuffers[1].colorBuffer,
		//	RSMBuffers[2].colorBuffer,
		//	RSMBuffers[3].colorBuffer,
		//}, RSMBuffers[4].depthBuffer);
	}

	private void OnPreRender() {
		Shader.EnableKeyword("ShadowPass");
		Shader.DisableKeyword("ShadingPass");
		foreach(var buf in RSMBuffers) {
			Graphics.SetRenderTarget(buf);
			GL.Clear(false, true, Color.black);
		}
		GL.Clear(true, true, Color.black, 1);
	}

	//private void OnRenderImage(RenderTexture source, RenderTexture destination) {
	//	Graphics.Blit(RSMBuffers[0], destination);
	//}
}
